import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:orginone/components/MySettingWidget/components/EditUserInfomationWidget/components/VerifyPhoneNumberWidget.dart';
import 'package:orginone/components/XButton/XButton.dart';
import 'package:orginone/components/XDialogs/dialog_utils.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/TabContainerWidget/types.dart';
import 'package:orginone/components/Tip/ToastUtils.dart';
import 'package:orginone/components/EntityWidget/common_fun.dart';
import 'package:orginone/components/MySettingWidget/components/EditUserInfomationWidget/components/UploudImage.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/core/public/consts.dart';
import 'package:orginone/main.dart';
import 'package:orginone/routers/pages.dart';

class EditUserInfomationWidget extends StatefulWidget {
  const EditUserInfomationWidget({Key? key}) : super(key: key);

  @override
  State<EditUserInfomationWidget> createState() => _EditUserInfomationState();
}

class _EditUserInfomationState extends State<EditUserInfomationWidget> {
  late TargetModel targetInfo;
  TextEditingController controllerName = TextEditingController();
  TextEditingController controllerCode = TextEditingController();
  TextEditingController controllerRemark = TextEditingController();

  @override
  void initState() {
    super.initState();
    if (null != relationCtrl.user) {
      targetInfo = TargetModel(
          id: relationCtrl.user!.id,
          name: relationCtrl.user!.name,
          code: relationCtrl.user!.code,
          remark: relationCtrl.user!.remark,
          typeName: relationCtrl.user!.typeName);
      controllerName.text = targetInfo.name ?? '';
      controllerCode.text = targetInfo.code ?? '';
      controllerRemark.text = targetInfo.remark ?? '';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          shadowColor: Colors.transparent,
          leading: IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: const Icon(
                Icons.arrow_back_ios,
                color: Colors.black,
              )),
          title: Text(
            "个人信息",
            style: XFonts.size24Black0,
          ),
          actions: [
            XButton.link(
              '提交',
              onPressed: () {
                submitUserInfo();
              },
            )
          ],
          backgroundColor: Colors.white,
        ),
        body: SingleChildScrollView(
            child: Column(
          children: [
            const Divider(
              color: XColors.dividerLineColor,
              height: 0.5,
            ),
            InkWell(
              highlightColor: Colors.transparent,
              radius: 0,
              onTap: () {
                selectList();
              },
              child: Container(
                margin: const EdgeInsets.only(bottom: 40),
                width: 80,
                height: 80,
                child: Stack(
                  clipBehavior: Clip.none,
                  alignment: Alignment.center,
                  children: [
                    _createImgAvatar(),
                    const Positioned(
                        right: 6,
                        top: 50,
                        child: Icon(Icons.camera_alt_rounded)),
                  ],
                ),
              ),
            ),
            _buildRowInfo("名称", controllerName),
            _buildRowInfo("手机号码", controllerCode),
            _buildRemark(),
            buildLogoutBtn()
          ],
        )));
  }

  buildLogoutBtn() {
    return Padding(
      padding: const EdgeInsets.all(5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          XButton.hollowMin(
            "注销账户",
            padding: 35,
            textStyle: const TextStyle(
                fontSize: 16, fontWeight: FontWeight.w600, color: Colors.red),
            onPressed: () {
              showCupertinoDialog(
                  context: navigatorKey.currentState!.context,
                  builder: buildConfirmDialog);
            },
          ),
          // GestureDetector(
          //   onTap: () {
          //     showCupertinoDialog(
          //         context: navigatorKey.currentState!.context,
          //         builder: buildConfirmDialog);
          //   },
          //   child: Container(
          //       margin: EdgeInsets.only(top: 12.h, right: 24.w),
          //       width: Get.width * 0.35,
          //       height: 40,
          //       alignment: Alignment.center,
          //       decoration: BoxDecoration(
          //         border: Border.all(color: Colors.red, width: 1),
          //         borderRadius: BorderRadius.circular(6),
          //       ),
          //       child: Text(
          //         "注销账户",
          //         style: TextStyle(
          //           color: Colors.red,
          //           fontSize: 22.sp,
          //           fontFamily: 'PingFang SC',
          //           fontWeight: FontWeight.w600,
          //         ),
          //       )),
          // ),
        ],
      ),
    );
  }

  Widget _buildRowInfo(String title, TextEditingController controller) {
    return Container(
        padding: const EdgeInsets.all(16),
        decoration: const BoxDecoration(
            border:
                Border(bottom: BorderSide(color: XColors.dividerLineColor))),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              title,
              style: TextStyle(
                color: Colors.black.withOpacity(0.6),
                fontSize: 22.sp,
                fontFamily: 'PingFang SC',
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
                child: TextField(
              style: TextStyle(
                color: Colors.black,
                fontSize: 22.sp,
                fontFamily: 'PingFang SC',
              ),
              textAlign: TextAlign.end,
              decoration: const InputDecoration(
                contentPadding: EdgeInsets.zero,
                isDense: true,
                hintText: "请输入",
                border: InputBorder.none,
              ),
              controller: controller,
              onChanged: (value) {},
            ))
          ],
        ));
  }

  Widget _buildRemark() {
    return Container(
        padding: const EdgeInsets.all(16),
        decoration: const BoxDecoration(
            border:
                Border(bottom: BorderSide(color: XColors.dividerLineColor))),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "简介",
              style: TextStyle(
                color: Colors.black.withOpacity(0.6),
                fontSize: 22.sp,
                fontFamily: 'PingFang SC',
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              style: TextStyle(
                color: Colors.black,
                fontSize: 22.sp,
                fontFamily: 'PingFang SC',
              ),
              maxLines: 5,
              decoration: const InputDecoration(
                contentPadding: EdgeInsets.zero,
                isDense: true,
                hintText: "请输入",
                border: InputBorder.none,
              ),
              controller: controllerRemark,
              onChanged: (value) {
                targetInfo.remark = value;
              },
            )
          ],
        ));
  }

  selectList() {
    return AlertDialogUtils.buildBottomModal(
        context,
        [
          ActionModel(
              title: "拍照",
              onTap: () async {
                dynamic res = await UploudImage().camera(context);
                getNewAvatar(res);
              }),
          ActionModel(
              title: "从相册选择",
              onTap: () async {
                dynamic res = await UploudImage().chooseImage(context);
                getNewAvatar(res);
              })
        ],
        isNeedPop: false);
  }

  ///处理头像
  getNewAvatar(dynamic res) async {
    var docDir = relationCtrl.user?.directory;
    if (res != null) {
      XFile pickedImage = res;
      var item = await docDir?.createFile(
        File(pickedImage.path),
      );
      if (item != null && null != relationCtrl.user) {
        targetInfo.icon = jsonEncode(item.shareInfo().toJson());
        updateAvatar(context);
      } else {
        ToastUtils.showMsg(msg: "上传失败，请稍后重试！");
      }
    }
  }

  updateAvatar(BuildContext context) async {
    bool? updateRes = await relationCtrl.user?.update(targetInfo);
    if (updateRes!) {
      ToastUtils.showMsg(msg: "更换头像成功");
      RoutePages.back(context);
      if (mounted) {
        setState(() {});
      }
    }
  }

  checkPhone() async {
    var res = await relationCtrl.auth.dynamicCode(DynamicCodeModel.fromJson({
      'account': controllerCode.text,
      'platName': '资产共享云',
      'dynamicId': '',
    }));
    if (res.success && res.data != null) {
      String dynamicId = res.data!.dynamicId;
      showDialog(
          context: context,
          builder: (context) => Center(
                child: Material(
                    color: Colors.transparent,
                    child: VerifyPhoneNumberWidget(
                        phoneNumber: controllerCode.text,
                        confirmFun: (yzm) async {
                          //验证验证码
                          var res = await relationCtrl.provider.verifyCodeLogin(
                              controllerCode.text, yzm, dynamicId);
                          if (res.success) {
                            updateUser();
                          } else {
                            ToastUtils.showMsg(msg: res.msg ?? '验证失败,请重试');
                          }
                          RoutePages.back(context);
                        })),
              ),
          barrierColor: Colors.black.withOpacity(0.6));
    } else {
      ToastUtils.showMsg(msg: '发送验证码失败，请稍后重试');
    }
  }

  submitUserInfo() async {
    if (controllerName.text.isEmpty) {
      return ToastUtils.showMsg(msg: "请输入名称");
    }
    if (controllerCode.text.isEmpty) {
      return ToastUtils.showMsg(msg: "请输入手机号码");
    }
    if (controllerRemark.text.isEmpty) {
      return ToastUtils.showMsg(msg: "请输入简介");
    }
    if (targetInfo.code != controllerCode.text) {
      //校验新手机号
      RegExp regex = RegExp(Constants.accountRegex);
      if (!regex.hasMatch(controllerCode.text)) {
        ToastUtils.showMsg(msg: "请输入正确的手机号");
        return;
      }
      await checkPhone();
    } else {
      updateUser();
    }
  }

  updateUser() async {
    targetInfo.name = controllerName.text;
    targetInfo.remark = controllerRemark.text;
    targetInfo.code = controllerCode.text;
    bool? res = await relationCtrl.user?.update(targetInfo);
    if (res!) {
      ToastUtils.showMsg(msg: "修改成功");
    }
  }

  ///头像
  Widget _createImgAvatar({BoxFit fit = BoxFit.cover, bool circular = true}) {
    dynamic avatar = XImage.entityIcon(
      relationCtrl.user,
      width: 60,
      circular: circular,
      radius: 30,
      fit: fit,
    );
    return Container(margin: const EdgeInsets.all(0), child: avatar);
  }
}
